package com.gwm.page.service;

import com.gwm.item.client.ItemClient;
import com.gwm.item.dto.*;
import com.gwm.seckill.client.SeckillClient;
import com.gwm.seckill.pojo.SeckillPolicyDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private SpringTemplateEngine engine ;

    public Map<String,Object> buildData(Long spuId) {
//        tb_spu
        Map<String,Object> dataMap = new HashMap<>();

        SpuDTO spu = itemClient.findSpuBySpuId(spuId);
//       spuName 商品名称
        dataMap.put("spuName",spu.getName());
//         categories  spu上三级分类的集合
        List<CategoryDTO> categories = itemClient.findCategoryListByIds(spu.getCategoryIds());
        dataMap.put("categories",categories);
//        brand  品牌对象
        BrandDTO brandDTO =  itemClient.findBrandByBrandId(spu.getBrandId());
        dataMap.put("brand",brandDTO);
//        subTitle  商品卖点
        dataMap.put("subTitle",spu.getSubTitle());
//        detail    spuDetail
        SpuDetailDTO spuDetail = itemClient.findSpuDetailBySpuId(spuId);
        dataMap.put("detail",spuDetail);
//        skus  当前spu下所有sku集合
        List<SkuDTO> skuList = itemClient.findSkuListBySpuId(spuId);
        dataMap.put("skus",skuList);

//        specs 带有规格参数的规格组集合
        List<SpecGroupDTO> specGroupList = itemClient.findSpecGroupByCategoryId(spu.getCid3());
       /* for (SpecGroupDTO specGroup : specGroupList) {
            List<SpecParamDTO> paramList = itemClient.findSpecParamByCategoryIdOrGroupId(null, specGroup.getId(), null);
            specGroup.setParams(paramList);
        }*/
        List<SpecParamDTO> specParamList = itemClient.findSpecParamByCategoryIdOrGroupId(spu.getCid3(), null, null);
        Map<Long, List<SpecParamDTO>> specParamGroup = specParamList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        specGroupList = specGroupList.stream().map(group->{
            group.setParams(specParamGroup.get(group.getId()));
            return group;
        }).collect(Collectors.toList());
        dataMap.put("specs",specGroupList);
        return dataMap;
    }


    public void createOneHtml(Long spuId){
        Context context = new Context();
        context.setVariables(this.buildData(spuId));

        try(PrintWriter writer = new PrintWriter(new File("D:\\class05\\nginx-1.16.0\\html\\item\\"+spuId+".html"),"UTF-8")) { //可以自动关闭流
            engine.process("item",context,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteHtml(Long spuId) {
        File file = new File("D:\\class05\\nginx-1.16.0\\html\\item\\" + spuId + ".html");
        file.delete();
    }

    @Autowired
    private TemplateEngine templateEngine;


    @Autowired
    private SeckillClient seckillClient;
    /**
     * 创建秒杀 列表页 和 详情页
     * @param date
     */
    public void createSecKillListAndDetailHtml(String date){
        try{
            //        根据时间获取秒杀规则列表
            List<SeckillPolicyDTO> secKillPolicyList = seckillClient.findSecKillPolicyList(date);
            //        获取秒杀规则列表
            if(!CollectionUtils.isEmpty(secKillPolicyList)){
                //        根据秒杀时间 获取并生成秒杀列表页面
                createSecKillListHtml(secKillPolicyList);
                //                生成秒杀的详情页面
                for (SeckillPolicyDTO seckillPolicyDTO : secKillPolicyList) {
                    createSecKillDetailHtml(seckillPolicyDTO);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error("获取秒杀信息 失败！");
        }
    }

    /**
     * 生成秒杀列表的静态页面，生成后放在nginx目录下的html\seckill 目录下，名字为 list.html
     *创建 秒杀列表的静态页面
     */
    public void createSecKillListHtml(List<SeckillPolicyDTO> secKillPolicyList){
        Context context = new Context();
        //获取秒杀列表 数据
        Map<String,Object> itemData = new HashMap<>();
        //        根据日期查询 秒杀列表
        itemData.put("seckillList",secKillPolicyList);
        //设置 动态数据
        context.setVariables(itemData);
//        File dir = new File("D:\\ITCAST\\ly\\nginx-1.16.0\\html\\seckill");
        File dir = new File("I:\\html\\seckill");
        if(!dir.exists()){
            dir.mkdir();
        }
        File itemFile = new File(dir,"list.html");
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(itemFile,"UTF-8");
            templateEngine.process("seckill-index",context,printWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            printWriter.close();
        }

    }

//生成秒杀详情，生成后放在nginx目录下的html\seckill 目录下，名字为 秒杀id.html
    /**
     * 创建 秒杀详情静态页面
     */
    public void createSecKillDetailHtml(SeckillPolicyDTO seckillPolicyDTO){
        //       秒杀规则id
        Long secKillId = seckillPolicyDTO.getId();
        //        模板上下文
        Context context = new Context();
        //获取秒杀商品的规格参数信息
        Map<String, Object> itemData = loadSecKillDetailData(seckillPolicyDTO);
        //设置 动态数据
        context.setVariables(itemData);
        //        模板目录,nginx下的html下的seckill
//        File dir = new File("D:\\ITCAST\\ly\\nginx-1.16.0\\html\\seckill");
        File dir = new File("I:\\html\\seckill");
        if(!dir.exists()){
            dir.mkdir();
        }
        //        要生成的文件名
        File itemFile = new File(dir,secKillId+".html");
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(itemFile,"UTF-8");
            //详情页模板名称为 seckill-item
            templateEngine.process("seckill-item",context,printWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            printWriter.close();
        }

    }

    /**
     * 获取秒杀详情信息，商品的规格参数
     * @param seckillPolicyDTO 秒杀 规则对象
     * @return
     */
    public Map<String, Object> loadSecKillDetailData(SeckillPolicyDTO seckillPolicyDTO) {
        Map<String,Object> map = new HashMap<>();
        Long spuId = seckillPolicyDTO.getSpuId();
        //获取spu detail
//        SpuDetailDTO spuDetailDTO = itemClient.findSpuDetailById(spuId);
        SpuDetailDTO spuDetailDTO = itemClient.findSpuDetailBySpuId(spuId);
        //规格组 和 组内规格
//        List<SpecGroupDTO> specGroupDTOList = itemClient.findSpecGroupWithParamByCid(seckillPolicyDTO.getCid3());
        List<SpecGroupDTO> specGroupDTOList = itemClient.findSpecGroupByCategoryId(seckillPolicyDTO.getCid3());
        map.put("seckillgoods",seckillPolicyDTO);
        map.put("detail",spuDetailDTO);
        map.put("specs",specGroupDTOList);
        return map;
    }










}
